package com.wewins.fota.controller;

import com.wewins.fota.bean.dto.ResponseRst;
import com.wewins.fota.common.constant.HttpConst;
import com.wewins.fota.common.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Throwable.class)
    public ResponseRst<String> handleException(Throwable e) {
        log.error("error happen:", e);
        return ResponseRst.<String>builder().build().withDefaultError(HttpConst.MSG_FAIL_SERVER_EXCEPTION);
    }


    // 实体绑定异常捕获
    @ExceptionHandler(BindException.class)
    public ResponseRst<List<String>> handleBindException(BindException e) {
        log.error("BindException happen:", e);
        return ResponseRst.<List<String>>builder()
                .data(CommonUtil.getRstStrings(e.getBindingResult()))
                .build()
                .withDefaultError(HttpConst.MSG_FAIL_BIND_PARAM_EXCEPTION);
    }

    // 实体绑定异常捕获
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseRst<List<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException happen:", e);
        return ResponseRst.<List<String>>builder()
                .data(CommonUtil.getRstStrings(e.getBindingResult()))
                .build()
                .withDefaultError(HttpConst.MSG_FAIL_BIND_PARAM_EXCEPTION);
    }

    // 单个参数绑定异常捕获
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseRst<List<String>> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("ConstraintViolationException happen:", e);
        List<String> defaultMsg = e.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return ResponseRst.<List<String>>builder().data(defaultMsg).build().withDefaultError(HttpConst.MSG_FAIL_BIND_PARAM_EXCEPTION);
    }
}
